package com.lzy.arithmetic;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class 三数之和 {

    /**
     * 排序+双指针
     */
    public static List<List<Integer>> sumThreeNums(int[] nums) {
        //长度小于3，没法玩
        if (nums == null || nums.length < 3) {
            return null;
        }
        Arrays.sort(nums);

        List<List<Integer>> anc = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {

            //首位大于0，没法玩
            if (nums[i] > 0) {
                break;
            }

            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int L = i + 1;
            int R = nums.length - 1;
            while (L < R) {
                int sum = nums[i] + nums[L] + nums[R];
                if (sum == 0) {
                    anc.add(Arrays.asList(nums[i], nums[L], nums[R]));
                    while (L < R && nums[L] == nums[L + 1]) L++;
                    while (L < R && nums[R] == nums[R - 1]) R--;
                    L++;
                    R--;
                } else if (sum < 0) {
                    L++;
                } else {
                    R--;
                }
            }

        }
        return anc;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{-1, 0, 1, 2, -1, -4};
        List<List<Integer>> result = sumThreeNums(nums);
        System.out.println(result.toArray());
    }
}
